package com.easy.web.controller.ord;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easy.common.core.R;
import com.easy.common.utils.ServletUtils;
import com.easy.user.pojo.Feedback;
import com.easy.user.service.IFeedbackService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

import static com.easy.common.utils.RedisConstants.LOGIN_USER_KEY;

/**
 * 反馈控制器
 *
 * @author RuoYu
 * @date 2023/01/08
 */
@Slf4j
@RestController
@RequestMapping("feedback")
@Api(tags = "反馈 控制器")
public class FeedbackController {

    @Autowired
    private IFeedbackService feedbackService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 添加反馈
     *
     * @param feedback 反馈
     * @return {@link R}
     */
    @PostMapping("add")
    @ApiOperation(value = "添加反馈")
    @ApiImplicitParam(name = "feedback", value = "反馈实体", required = true)
    public R addFeedback(@RequestBody Feedback feedback) {
        log.info("feedback{}", feedback);
        String token = LOGIN_USER_KEY + ServletUtils.getRequest().getHeader("authorization");
        Object uid = stringRedisTemplate.opsForHash().get(token, "Id");
        feedback.setCreateTime(LocalDateTime.now());
        log.info(token + "======" + uid);
        if (uid != null) {
            feedback.setUserId(Long.valueOf(uid + ""));
        }
        boolean flag = feedbackService.addFeedback(feedback);
        if (flag) {
            return R.success();
        }
        return R.error();
    }

    /**
     * 得到反馈
     *
     * @return {@link R}
     */
    @GetMapping
    @ApiOperation(value = "通过uid获取反馈信息反馈")
    public R getFeedback(Long id) {
        Feedback feedback = feedbackService.getFeedback(id);
        return R.success(feedback);
    }

    /**
     * 得到反馈
     *
     * @param page     页面
     * @param pageSize 页面大小
     * @return {@link R}<{@link Page}<{@link Feedback}>>
     */
    @GetMapping("list")
    @ApiOperation(value = "通过uid获取反馈信息反馈列表")
    public R<Page<Feedback>> getFeedbackList(int page, int pageSize) {
        String token = LOGIN_USER_KEY + ServletUtils.getRequest().getHeader("authorization");
        Long uid = Long.valueOf(stringRedisTemplate.opsForHash().get(token, "Id") + "");
        Page<Feedback> feedbackList = feedbackService.getFeedbackList(page, pageSize, uid);
        return R.success(feedbackList);
    }

}
